import { makeAutoObservable, } from "mobx";
import ChartsConfig from "../config/ChartsConfig";
import { Assets, CashFlows, Incomes, LatestRecommendations, StatisticResponse, StatisticType, Strategies, StrategyLine, Summary } from "../services/StatisticService";
import { StockSymbol, WatchListService, WatchMarket, WatchMarketService, WatchSymbolData } from "../services/WatchlistService";
import ChartStore from "./ChartStore";


class StatisticStore {
    chart: any;
    summary?: Summary;
    incomes?: Incomes;
    assets?: Assets;
    cashFlows?: CashFlows;
    recommendations: LatestRecommendations[] = [];
    strategies: Array<Strategies> = [];
    strategyLines: Array<StrategyLine> = [];
    symbols: StockSymbol[] = [];
    private _symbols: StockSymbol[] = [];
    checkedPosition: string = '0';
    type: StatisticType = StatisticType.incomes;
    noData: boolean = false;
    marketLoading: boolean = false;
    markets?: WatchMarket;
    constructor() {
        makeAutoObservable(this);
    }


    public async getWatchMarketlist() {
        var response: WatchMarket;
        this.marketLoading = true;
        try {
            response = await new WatchMarketService().send();
        } catch (e) {
            console.log("getWatchlist error ", e);
            this.marketLoading = false;
            return;
        }
        this.marketLoading = false;
        this.markets = response;
    }


    public async getWatchSymbolist() {
        var response: WatchSymbolData;
        try {
            response = await new WatchListService().send();
        } catch (e) {
            console.log("getWatchlist error ", e);
            return;
        }
        this._symbols = response.symbol_and_name;
    }

    public onSearchInputChange(keyword: string) {
        var _symbols: StockSymbol[] = JSON.parse(JSON.stringify(this._symbols));
        var _keyword: string = keyword.toLowerCase();
        if (!_keyword) {
            this.symbols = []
        } else {
            this.symbols = _symbols.filter((s) => {
                var isSymbolContained = s.symbol.toLowerCase().indexOf(_keyword) > -1;
                var isNameContained = s.name.toLowerCase().indexOf(_keyword) > -1;
                return isSymbolContained || isNameContained;
            });
        }
    }


    public async paintChart(statisticData?: StatisticResponse) {
        console.log("paintChart paintChartpaintChart 。。。");

        if (statisticData && !statisticData?.finances) {
            this.noData = true;
            return;
        }
        this.noData = false;
        if (statisticData) {
            var _strategyLineMap = {};
            var _strategyLines: StrategyLine[] = [];
            this.incomes = statisticData.finances.incomes;
            this.assets = statisticData.finances.assets;
            this.cashFlows = statisticData.finances.cash_flows;
            this.summary = statisticData.summary;
            this.recommendations = statisticData.latest_recommendations;
            this.strategies = statisticData.strategies;
            statisticData.strategies.forEach((s) => {
                _strategyLineMap[s.strategy_name] = _strategyLineMap[s.strategy_name] || [];
                _strategyLineMap[s.strategy_name].push(s);
            })
            for (var key in _strategyLineMap) {
                _strategyLines.push({ strategy_name: key, strategies: _strategyLineMap[key] });
            }
            this.strategyLines = _strategyLines;
        } else if (!this.chart) {
            return;
        }
        setTimeout(() => {
            this.handleTabChange(StatisticType.incomes, true, 0);
        }, 0);
    }



    handleTabChange(type: StatisticType, init: boolean = false, index: number) {
        var Highcharts: any = (window as any).Highcharts;
        var line1: Array<Array<number>> = [], line2: Array<Array<number>> = [];
        this.type = type;
        this.checkedPosition = ((100 / 3) * index) + '%';
        switch (this.type) {
            case StatisticType.incomes:
                var datesIncomes: Array<string> = this.incomes?.financial_years || [];
                var revenues: Array<number> = this.incomes?.total_revenues || [];
                var incomes: Array<number> = this.incomes?.net_incomes || [];
                for (let i = 0; i < datesIncomes.length; i++) {
                    line1.push([Date.parse(datesIncomes[i]), revenues[i]]);
                    line2.push([Date.parse(datesIncomes[i]), incomes[i]]);
                }
                break;
            case StatisticType.assets:
                var datesAssets: Array<string> = this.assets?.financial_years || [];
                var revenuesAssets: Array<number> = this.assets?.total_assets || [];
                var liabs: Array<number> = this.assets?.total_liabs || [];
                for (let i = 0; i < datesAssets.length; i++) {
                    line1.push([Date.parse(datesAssets[i]), revenuesAssets[i]]);
                    line2.push([Date.parse(datesAssets[i]), liabs[i]]);
                }
                break;
            case StatisticType.cashFlows:
                var datesCashFlows: Array<string> = this.cashFlows?.financial_years || [];
                var cashes: Array<number> = this.cashFlows?.cashes || [];
                var changeInCashes: Array<number> = this.cashFlows?.change_in_cashes || [];
                for (let i = 0; i < datesCashFlows.length; i++) {
                    line1.push([Date.parse(datesCashFlows[i]), cashes[i]]);
                    line2.push([Date.parse(datesCashFlows[i]), changeInCashes[i]]);
                }
                break;
        }
        line1.sort((a, b) => a[0] - b[0]);
        line2.sort((a, b) => a[0] - b[0]);
        if (this.chart && !init) {
            this.chart.series[0].update({ data: line1 });
            this.chart.series[1].update({ data: line2 });
        } else {
            if (ChartStore.stockTab === 1) {
                this.chart = Highcharts.stockChart('statisticChart', ChartsConfig.setStatisticChart(line1, line2));
                this.chart.isSubChart = true;
            }
        }
    }
}

export default new StatisticStore();